<template>
	<view class="Shell">
		<view v-if="canIUse&&platcanIUse">
			<view class='header'>
				<image mode='aspectFit' :src='masterDomain+"/include/json.php?action=getSystemLogo"'></image>
			</view>

			<view class='content'>
				<text> 您暂未授权小程序获取您的信息，为了提供更好的服务，请点击“授权登录”按钮，允许头像和昵称等信息的授权。</text>
			</view>
			<button v-if="canIUseGetUserProfile" class='bottom' type='primary'
				@click="agreeb?getUserProfile():checkAgree()" data-eventsync="true"> {{platText}}授权登录
			</button>
			<button v-if="canIUseGetUserProfile && !miniProgramBindPhone" class='bottom' type='cancel' @click="backFn">
				取消 </button>
			<view v-if="miniProgramBindPhone" class='link' @click="loginTo"> 其他方式登陆 / 注册 </view>
		</view>

		<view v-else>
			<view class='header'>
				<image mode='aspectFit' :src='masterDomain+"/include/json.php?action=getSystemLogo"'></image>
			</view>
			<button v-if="!agreeb" class='bottom' type='primary' @click="checkAgree"> {{platText}}手机号码快捷登录 </button>
			<button v-else class='bottom' type='primary' open-type="getPhoneNumber"
				@getphonenumber="platcanIUse?getPhoneNumber($event):wxLogin($event)">
				{{platText}}手机号码快捷登录 </button>
			<view v-if="canIUseGetUserProfile" class='link' @click="loginTo"> 其他方式登陆 / 注册 </view>
		</view>
		<view class="fixedBottom">
			<view :class="`agreebtn ${agreeb?'checked':''}`" @click="agree">
				<view class="gou"></view>同意
			</view>
			<view @click="linkTo(1)" class="linkTo">《用户注册协议》</view>和
			<view @click="linkTo(2)" class="linkTo">《隐私协议》</view>
		</view>
		<!-- 弹窗提示 -->
		<popWarn :info="info" :warningb="warningb"></popWarn>
		<private_tip :privateShow="privateb"></private_tip>
	</view>
</template>

<script>
	var _this;
	var timer; //提醒弹窗定时器
	// 引入底部组件
	import popWarn from '/components/popWarn/popWarn.vue';
	const app = getApp();
	export default {
		components: { //组件注册
			popWarn
		},
		data() {
			return {
				imgsrc: `${app.globalData.masterDomain}/static/images/miniprograme/task/`,
				imgVersion: app.globalData.imgVersion,
				//判断小程序的API，回调，参数，组件等是否在当前版本可用。
				// canIUse: tt.canIUse('button.open-type.getPhoneNumber'),
				canIUse: true,
				canIUseGetUserProfile: false,
				masterDomain: app.globalData.masterDomain,
				fromShare: 0,
				userData: {},
				// 组件数据
				warningb: false,
				info: '',
				miniProgramBindPhone: '',
				agreeb: false,
				privateb: false,
				// 平台兼容项
				reqUrl: '',
				platText: '',
				platcanIUse: true
			}
		},
		beforeCreate() {
			// #ifdef H5
			uni.redirectTo({
				url: `/pages/redirect/index?url=${encodeURIComponent(app.globalData.masterDomain+'/login.html')}`
			})
			// #endif
		},
		onLoad(options) {
			_this = this;
			if (app.globalData.wxprivate == -1) {
				app.watchG('wxprivate', function(value) {
					_this.wxprivate = value;
					if (value) { //弹出弹窗
						_this.privateb = true;
					} else {
						_this.onload(options);
					}
				})
			} else {
				if (app.globalData.wxprivate) { //弹出弹窗
					_this.privateb = true;
				} else {
					_this.onload(options);
				}
			}
		},
		methods: {
			onload(options) {
				// 从原生页面登录
				if (options.wxMiniProgramLogin && options.wxMiniProgramLogin == 1) {
					_this.wxMiniProgramLogin = 1;
				}
				if (options.path && options.path != '' || options.url && options.url != '') {
					_this.path = options.path || options.url;
				}
				if(decodeURIComponent(this.path).indexOf('forcelogout=1') > -1){
					_this.path = encodeURIComponent(decodeURIComponent(this.path).replace(/forcelogout=1/g, ''));
				}
				// 平台切换:搜索修改的变量即可知道哪里做过兼容-----------------
				let platForm = app.globalData.platForm;
				if (platForm == 'mp-weixin') { //微信
					let account_info = uni.getAccountInfoSync()
					let appid = account_info.miniProgram && account_info.miniProgram.appId || '';
					let path = _this.path && _this.path != '' ? ('&path=' + _this.path) : '';
					this.reqUrl = `include/ajax.php?service=member&action=wxMiniProgramConnect&appid=${appid}&fromShare=` +
						_this.fromShare + path;
					this.platcanIUse = false;
				} else if (platForm == 'mp-toutiao') { //抖音
					let path = _this.path && _this.path != '' ? ('&path=' + _this.path) : '';
					let wxMiniProgramLogin = _this.wxMiniProgramLogin && _this.wxMiniProgramLogin != '' ? (
						'&wxMiniProgramLogin=' + _this.wxMiniProgramLogin) : '';
					this.reqUrl = 'include/ajax.php?service=member&action=byteMiniProgramConnect&fromShare=' + _this
						.fromShare + path + wxMiniProgramLogin;
					this.platText = '抖音'
				}
				//---------------------------------------------------------
				if (options.back && options.back == 1 || options.path && options.path != '') { //从我的页面登陆和原生页面
					_this.back = 1
				}
				//从H5登录页点击微信快捷登录，这种情况需要强制显示第一步的授权页面
				if (options.authorize) {
					_this.authorize = 1
				}
				if (options.fromShare) { //从我的页面登陆
					_this.fromShare = options.fromShare
				}
				//是否需要获取手机号码，注意：等于0表示需要获取手机号码（默认情况），等于1表示不需要
				let miniProgramBindPhone = parseInt(app.globalData.dyConfig.bindphone);
				_this.miniProgramBindPhone = miniProgramBindPhone;
				//强制显示授权页面
				if (options.authorize) {}
				//是否显示获取手机号码页面，注意：等于0表示需要获取手机号码（默认情况），等于1表示不需要
				else if (miniProgramBindPhone == 0) {
					uni.getStorage({
						key: 'applyUserInfo',
					})
				}
				if (uni.getUserProfile) {
					_this.canIUseGetUserProfile = true
				}
				uni.login({
					success: res => {
						_this.code = res.code
					}
				});
				_this.redirect = options.url;
				_this.agreeData();
			},
			warnFn(timeout = 2000) { //弹窗提醒
				this.warningb = true;
				clearTimeout(timer);
				timer = setTimeout(res => {
					this.warningb = false;
				}, timeout);
			},
			backFn() { //后退函数
				uni.navigateBack({
					delta: 1,
					fail: res => {
						uni.redirectTo({
							url: '/pages/index/index',
						})
					}
				});
			},
			getUserProfile(e) { //获取用户信息
				// 推荐使用tt.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				//是否需要获取手机号码，注意：等于0表示需要获取手机号码（默认情况），等于1表示不需要
				let miniProgramBindPhone = parseInt(_this.miniProgramBindPhone);
				let code = '';
				uni.login({
					success: res => {
						code = res.code;
						_this.code = res.code
					}
				})
				uni.getUserProfile({
					// lang: 'zh_CN',
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						let userData = {
							code: _this.code,
							iv: res.iv,
							encryptedData: res.encryptedData,
							redirect: _this.redirect,
							nickname: res.userInfo.nickName,
							photo: res.userInfo.avatarUrl,
							city: res.userInfo.city,
							province: res.userInfo.province,
							gender: res.userInfo.gender,
						};
						_this.userData = userData;
						// 存储本地
						if (!miniProgramBindPhone) {
							_this.canIUse = false;
							uni.setStorage({
								key: 'applyUserInfo',
								data: 1
							})
							//不需要获取手机号码的情况，直接进行登录
						} else {
							_this.request(1);
						}
					},
					fail: (res) => {
						if (res.errNo == 10200) {
							uni.showToast({
								title: '已拒绝小程序获取信息',
								icon: 'none',
								duration: 2000
							})
						} else {
							let title = '错误信息'
							uni.showModal({
								title: title + res.errNo,
								content: res.errMsg,
								showCancel: false,
							})
						}

					}
				})
			},
			getPhoneNumber(data) { //获取电话号码
				let phoneData;
				if (!data.detail.encryptedData && !data.detail.iv) {
					let errTip = data.detail.errMsg
					let title = '错误信息'
					if (data.detail.errMsg == 'getPhoneNumber:fail auth deny') {
						errTip = '当前小程序没有手机登录的权限，请使用其他方式登录';
						title = '错误信息：' + data.detail.errMsg
					}
					uni.showModal({
						title: title,
						content: errTip,
						showCancel: false,
					})
					return false;
				}
				if (!_this.userData && 1 == 2) {
					uni.login({
						success: res => {
							let code = res.code;
							uni.getUserInfo({
								lang: 'zh_CN',
								success: function(res) {
									_this.userData = {
										code: code,
										encryptedData: res.encryptedData,
										iv: res.iv,
										redirect: _this.redirect,
									};
									uni.login({
										success: res => {
											phoneData = {
												code: res.code,
												encryptedData: data.detail
													.encryptedData,
												iv: data.detail.iv
											}
											_this.phoneData = phoneData;
											_this.request();
										}
									});
								},
								error: function(res) {
									_this.info = res.data;
									return false;
								}
							})
						}
					});
				} else {
					uni.login({
						success: res => {
							phoneData = {
								code: res.code,
								encryptedData: data.detail.encryptedData,
								iv: data.detail.iv
							};
							_this.phoneData = phoneData;
							_this.request();
						}
					});
				}
			},
			wxLogin(data) {
				let phoneData;
				if (!data.detail.encryptedData && !data.detail.iv) {
					uni.showToast({
						title: '已拒绝小程序授权登录',
						icon: 'none',
						duration: 2000
					})
					return false;
				}
				uni.login({
					success: res => {
						phoneData = {
							code: data.detail.code,
							encryptedData: data.detail.encryptedData,
							iv: data.detail.iv
						};
						_this.phoneData = phoneData;
						_this.$set(_this.userData, 'code', res.code);
						_this.request();
					}
				});
			},
			checkAgree() {
				uni.showToast({
					title: '请先同意并勾选《用户注册协议》和《隐私协议》',
					icon: 'none',
					success: res => {
						setTimeout(res => {
							uni.hideToast();
						}, 2000)
					}
				})
			},
			agreeData() { //相关政策
				let randomNum = new Date().valueOf();
				_this.$ajax.get({
					url: 'api/appConfig.json?v=' + randomNum
				}).then(res => {
					_this.protocol = res.data.protocol;
				})
			},
			linkTo(index) {
				let type = index;
				let url = '';
				if (type == '1') {
					url = _this.protocol['用户注册协议'];
				} else if (type == '2') {
					url = _this.protocol['隐私政策'];
				}
				uni.navigateTo({
					url: '/pages/redirect/index?url=' + encodeURIComponent(url)
				})
			},
			request(type) {
				uni.showLoading({
					title: '登录中...',
				});
				_this.$ajax.post({
					url: `${_this.reqUrl}&base64=1`,
					data: `phoneData=${app.base64('encode',unescape(encodeURIComponent(JSON.stringify(_this.phoneData))))}&userData=${app.base64('encode',unescape(encodeURIComponent(_this.userData ? JSON.stringify(_this.userData) : ""))) }`
				}).then(res => {
					if (res.data) {
						let data = res.data;
						if (data.state == 100) {
							uni.removeStorageSync('logoutSelf'); //删除手动退出登路
							let userid = '';
							let access_token = '';
							let refresh_token = '';
							let urlParam = data.info.split('?')[1];
							userid = app.getUrlPara(urlParam, 'uid');
							access_token = app.getUrlPara(urlParam, 'access_token');
							refresh_token = app.getUrlPara(urlParam, 'refresh_token');
							uni.setStorageSync("userid", userid)
							uni.setStorageSync("access_token", access_token)
							uni.setStorageSync("refresh_token", refresh_token)
							let token_expired = Date.parse(new Date()) / 1000 + 7200 -
								20; //两个小时有效期，保险起见，用1小时59分钟40秒
							uni.setStorageSync("token_expired", token_expired)
							app.globalData.userid = userid;
							app.memberInfo(userid); //用户信息获取
							app.globalData.access_token = access_token;
							app.globalData.refresh_token = refresh_token;
							app.globalData.token_expired = token_expired;
							if (decodeURIComponent(_this.path).indexOf('/pages/') > -1) { //原生页面
								uni.navigateBack({
									delta: 1,
									fail: function() {
										//没有上一页，在当前页直接打开
										uni.redirectTo({
											url: '/pages/redirect/index?url=' +
												encodeURIComponent(data.info)
										})
									}
								})
							} else { //h5
								//H5去除forecelogout
								let str = _this.path;
								str = str.indexOf('forcelogout&') > -1 ? str.replace('forcelogout&', '') : str
									.replace('&forcelogout', '');
								let url = app.addUrlParam(str);
								uni.redirectTo({
									url: '/pages/redirect/index?url=' + encodeURIComponent(url)
								})
							}
							uni.getStorage({ //分享绑定
								key: 'fromShare',
								success: res => {
									app.bindShareFn(res.data);
								}
							});
						} else {
							uni.hideLoading();
							uni.showModal({
								title: '温馨提示',
								content: data.info,
								showCancel: false,
							})

							_this.userData = {}; //重置
							_this.canIUse = true; //重置
						}
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '授权失败！',
							icon: 'none',
							duration: 2000
						})
						_this.userData = {}; //重置
						_this.canIUse = true; //重置
					}
				}).catch(res => {
					console.log(res);
					uni.showToast({
						title: '登录失败！',
						icon: 'none',
						duration: 2000
					})
					_this.userData = {}; //重置
					_this.canIUse = true; //重置
				})
			},
			// 跳转登陆页面
			loginTo() {
				let path = _this.path && _this.path != '' ? ('path=' + _this.path) : '';
				let wxMiniProgramLogin = _this.wxMiniProgramLogin && _this.wxMiniProgramLogin != '' ? (
					'&wxMiniProgramLogin=' + _this.wxMiniProgramLogin) : '';
				let fromShare = uni.getStorageSync('fromShare');
				let url = '/pages/redirect/index?url=' + encodeURIComponent(app.addUrlParam(`${app.globalData
					.masterDomain}/login.html?from=wxmini&forcelogout=1&${path}&fromShare=${fromShare||''}${wxMiniProgramLogin}`,
					'forcelogout'))
				if (_this.back && _this.back == 1) {
					console.log(decodeURIComponent(url));
					uni.navigateTo({
						url: url
					})
				} else {
					uni.navigateBack();
				}
			},
			agree() {
				this.agreeb = !this.agreeb;
			},
		},
		watch: {
			info(newVal, oldVal) { //弹窗提示 
				if (newVal != '') {
					this.warnFn();
					setTimeout(res => { //重置，这样下次必会被监听到
						this.info = '';
					}, 2200)
				}
			}
		},
		onShareAppMessage(res) {
			let config = app.globalData.appConfig;
			return {
				title: config.share.title,
				desc: config.share.description,
				path: '/pages/index/index',
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
		// 分享到朋友圈
		onShareTimeline() {
			return {
				title: config.share.title,
				imageUrl: app.globalData.masterDomain + '/include/json.php?action=getSystemLogo'
			};
		},
	}
</script>

<style>
	@import url("./index.css");
</style>